#include "mainwindow.h"
#include <QStandardItemModel>
#include <qwt_plot_grid.h>
#include <qwt_plot_layout.h>
#include <QDebug>
#include "ui_mainwindow.h"
#define PROCESS_COL 8
//#include "QSplitter"

#include <qwt_thermo.h>

class ValueBar: public QWidget
{
public:
        ValueBar(Qt::Orientation orientation,
                 const QString &text, QWidget *parent, double value = 0.0):
        QWidget(parent)
        {
                d_label = new QLabel(text, this);
                d_label->setFont(QFont("Helvetica", 10));

                d_thermo = new QwtThermo(this);
                d_thermo->setRange(0.0,100.0);
                d_thermo->setValue(value);
                d_thermo->setFont(QFont("Helvetica", 8));
                d_thermo->setPipeWidth(6);
                d_thermo->setScaleMaxMajor(6);
                d_thermo->setScaleMaxMinor(5);
                d_thermo->setMargin(10);
                d_thermo->setFillColor(QColor("DarkMagenta"));

                QVBoxLayout *layout = new QVBoxLayout(this);
                layout->setMargin(0);
                layout->setSpacing(0);

                if ( orientation == Qt::Horizontal )
                {
                        d_label->setAlignment(Qt::AlignCenter);
                        d_thermo->setOrientation(orientation, QwtThermo::BottomScale);
                        layout->addWidget(d_label);
                        layout->addWidget(d_thermo);
                }
                else
                {
                        d_label->setAlignment(Qt::AlignRight);
                        d_thermo->setOrientation(orientation, QwtThermo::LeftScale);
                        layout->addWidget(d_thermo, 10, Qt::AlignHCenter);
                        layout->addWidget(d_label, 0);
                }
        }

        void setValue(double value)
        {
                d_thermo->setValue(value);
        }
private:
        QLabel *d_label;
        QwtThermo *d_thermo;
};

int MainWindow::interval = 1;//default interval
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
   // QRegExp reg("[1-9][0-9]{1,5}");
    this->ui->hostportLineEdit->setValidator(new QIntValidator(0,65535,this));
    this->ui->hostnameLineEdit->setText("127.0.0.1");
    this->ui->hostportLineEdit->setText("12345");
    this->ui->closeConnectPushButton->setEnabled(false);


    this->m_newList=false;
    process_model=new QStandardItemModel(0,PROCESS_COL,this);
    process_model->setHeaderData(0,Qt::Horizontal,QObject::trUtf8("PID"));
    process_model->setHeaderData(1,Qt::Horizontal,QObject::trUtf8("USER"));
    process_model->setHeaderData(2,Qt::Horizontal,QObject::trUtf8("STATUS"));
    process_model->setHeaderData(3,Qt::Horizontal,QObject::trUtf8("RSS"));
    process_model->setHeaderData(4,Qt::Horizontal,QObject::trUtf8("PPID"));
    process_model->setHeaderData(5,Qt::Horizontal,QObject::trUtf8("CPU%"));
    process_model->setHeaderData(6,Qt::Horizontal,QObject::trUtf8("MEM%"));
    process_model->setHeaderData(7,Qt::Horizontal,QObject::trUtf8("COMMAND"));
    this->ui->processTreeView->setModel(this->process_model);

    QColor c = QColor(0,255,0,255);
  //  c.setAlpha(150);
  //  setPen(c);
  //  setBrush(c);
    this->cpu_curve = new QwtPlotCurve("cpu percent");
    this->cpu_curve->setPen(c);
    this->cpu_curve->setBrush(c);
//    Background *bk = new Background();
 //   bk->attach(this->ui->cpuQwtPlot);
    this->ui->cpuQwtPlot->setCanvasBackground(QColor(Qt::black));
    (this->ui->cpuQwtPlot->plotLayout())->setAlignCanvasToScales(true);
    this->ui->cpuQwtPlot->setTitle("CPU USAGE");
    QwtPlotGrid *grid = new QwtPlotGrid;
    QColor gridcolor=QColor(0,128,64,255);
    grid->setMajPen(QPen(gridcolor,0,Qt::SolidLine));
    grid->setMinPen(QPen(gridcolor,0,Qt::SolidLine));
    grid->enableXMin(true);
    grid->enableYMin(true);
    grid->attach(this->ui->cpuQwtPlot);
    this->cpu_curve->attach(this->ui->cpuQwtPlot);


    this->ui->cpuPercentThermo->setRange(0.0,100.0);
    this->ui->cpuPercentThermo->setFillColor(gridcolor);




    for(int i = 0;i<HISTORY;i++){
            this->y[i] = 0.0;
            this->x[i]=i*1.0;
    }
    this->ui->cpuQwtPlot->setAxisScale(QwtPlot::xBottom,0,HISTORY);
    this->ui->cpuQwtPlot->setAxisScale(QwtPlot::yLeft,0,100);

}
void MainWindow::connectToServer(){
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_connectPushButton_released()
{
        QString hostname = this->ui->hostnameLineEdit->text();
        quint16 port = this->ui->hostportLineEdit->text().toInt();

        this->m_connection = new Connection(this);
        this->m_connection->connectToHost(hostname,port);

        connect(this->m_connection,SIGNAL(readyRead()),this,SLOT(readServerData()));
        connect(this->m_connection,SIGNAL(connected()),this,SLOT(connected()));//connect the push button to the connection
        connect(this->m_connection,SIGNAL(disconnected()),this,SLOT(closeConnection()));
        connect(this->m_connection,SIGNAL(destroyed()),this,SLOT(closeConnection()));
        this->m_connection->waitForConnected();


        this->m_connection->write(QString("INTERVAL:%1\r\n").arg(MainWindow::interval).toAscii());
        this->m_connection->flush();
       // this->m_connection->write(QString("START\r\n").toAscii());
       // this->m_connection->flush();
}
void MainWindow::readServerData()
{
        if(!this->m_connection->canReadLine())
                return;
        QTextStream in(this->m_connection);
        //in.setCodec(QTextCodec::codecForName("UTF-8"));
        QString res = in.readLine();
        while(res !=  ""){
                qDebug()<<res;
                parseMsg(res);
                res = in.readLine();
        }

}
void MainWindow::parseMsg(QString msg){
        QStringList sl = msg.split("~");
        for( int i = 0; i < sl.size(); i++){
                QString ls = sl.at(i).toLocal8Bit().constData();
                QStringList lsl = ls.split(",");
                QString tmp = lsl.at(0);

                if(tmp.startsWith(QChar('e'))){
                        qDebug()<<"eth:"<<ls;
                        displayEth(lsl);
                }
                else if(tmp == "Process"){
                        qDebug()<<"process:";
                        displayProcess(lsl);
                }
                else if(tmp == "Cpu"){
                        qDebug()<<"cpu:";
                        displayCpu(lsl);
                        this->m_newList=true;//one freme has ended & another started
                }
                else if( tmp == "Mem" ){
                        qDebug()<<"mem:";
                        displayMem(lsl);
                }
                else if( tmp == "LoadAverage"){
                        qDebug()<<"load Average";
                        displayAvg(lsl);
                }
                else if ( tmp == "Cpuinfo" ){
                        qDebug()<<"Hwinfo";
                        displayHw(lsl);
                }
                else if ( tmp == "Version" ){
                        qDebug()<<"Version";
                        displayVer(lsl);
                        this->ui->cpuInfoTtextBrowser->clear();
                }
                else if ( tmp == "Hostname" ){
                        qDebug()<<"Hostname";
                        displayHost(lsl);
                }
                else{
                        qDebug()<<"bad msg from server"<<ls;
                }
        }
}
void MainWindow::displayProcess(QStringList msg){

        static int rowCount;
        if(this->m_newList){
                this->m_newList=false;
                this->process_model->removeRows(0,rowCount);
                rowCount = 0;
        }
        this->process_model->insertRow(rowCount);
        for(int index = 1; index < msg.count(); index++)
        {
                QString temp = msg.at(index);
                  QStandardItem *item = new QStandardItem(temp);
                  this->process_model->setItem(rowCount,index-1,item);
        }
        rowCount++;

}
void MainWindow::displayCpu(QStringList msg){
        int percent = msg.at(1).toInt();
        y[HISTORY] = percent/10.0;
        for (int i = 0; i < HISTORY;i++) {
                y[i] = y[i+1];
        }
        this->cpu_curve->setRawSamples(this->x,this->y,HISTORY);
        this->ui->cpuQwtPlot->replot();
}

void MainWindow::displayEth(QStringList msg){
        this->ui->recv_bytesLabel->setText(msg.at(1));
        this->ui->recv_packetsLabel->setText(msg.at(2));
        this->ui->send_bytesLabel->setText(msg.at(3));
        this->ui->send_packetsLabel->setText(msg.at(4));
}

void MainWindow::displayMem(QStringList msg){
        this->ui->mem_usedLabel->setText(msg.at(1));
        this->ui->mem_freeLabel->setText(msg.at(2));
        this->ui->mem_sharedLabel->setText(msg.at(3));
        this->ui->mem_buffLabel->setText(msg.at(4));
        this->ui->mem_cachedLabel->setText(msg.at(5));
}

void MainWindow::displayAvg(QStringList msg){
        msg.pop_front();
        this->ui->load_AvgLabel->setText(msg.join("   "));
}
void MainWindow::displayHw(QStringList msg){
        msg.pop_front();
        this->ui->cpuInfoTtextBrowser->append(msg.join(" "));
}
void MainWindow::displayVer(QStringList msg){
        this->ui->versionTextBrowser->setText(msg.at(1));

}

void MainWindow::displayHost(QStringList msg){
        this->ui->hostnameLabel->setText(msg.at(1));
}
void MainWindow::connected(){
        this->ui->connectPushButton->setEnabled(false);
        this->ui->closeConnectPushButton->setEnabled(true);
}
void MainWindow::closeConnection(){
        this->ui->connectPushButton->setEnabled(true);
        this->ui->closeConnectPushButton->setEnabled(false);
}
void MainWindow::on_closeConnectPushButton_released(){
        this->m_connection->close();
}

